package com.autumn.platform.web.argumentresolver;

import java.lang.reflect.Field;

import org.springframework.core.MethodParameter;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.autumn.platform.core.Utils;
import com.autumn.platform.core.context.user.ISessionUser;
import com.autumn.platform.web.WebHolder;
import com.autumn.platform.web.annotation.User;

public class SessionUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return ISessionUser.class.isAssignableFrom(parameter.getParameterType())
                || parameter.hasParameterAnnotation(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        ISessionUser sessionUser = WebHolder.getSessionUser();
        if (null != sessionUser) {
            Class<?> cls = parameter.getParameterType();
            if (ISessionUser.class.isAssignableFrom(cls)) {
                return sessionUser;
            } else {
                User anno = parameter.getParameterAnnotation(User.class);
                if (null == anno || Utils.isBlank(anno.value())) {
                    return sessionUser.getUserId();
                } else {
                    Field field = ReflectionUtils.findField(sessionUser.getClass(), anno.value());
                    return field.get(sessionUser);
                }
            }
        }
        return null;
    }

}
